package tc.maas.eikotrade.dataaccess;

import java.util.Map;
import java.util.Map.Entry;
import org.apache.log4j.Logger;

//import org.apache.log4j.Logger;
import org.neodatis.odb.ODB;
import org.neodatis.odb.ODBFactory;
import org.neodatis.odb.Objects;
import org.neodatis.odb.impl.core.query.criteria.CriteriaQuery;
import org.neodatis.odb.impl.core.query.criteria.EqualCriterion;

public class DataManager {

    Logger LOG = Logger.getLogger(DataManager.class);
    private static final String DATABASE = "data.odb";
    ODB odb;

    public void store(Storable storable) {
        try {
            odb = ODBFactory.open(DATABASE);
            odb.store(storable);
            odb.close();
        } catch (Exception e) {
            LOG.error(e);
        }
    }

    public void store(Comparable comparable) {
        try {
            odb = ODBFactory.open(DATABASE);
            odb.store(comparable);
            odb.close();
        } catch (Exception e) {
            LOG.error(e);
        }
    }

    public <T extends Storable> T findStorable(Class itemClassToFind, Map<String, String> criteria) throws Exception {
        CriteriaQuery query = new CriteriaQuery(itemClassToFind);
        for (Entry<String, String> entry : criteria.entrySet()) {
            query.setCriterion(new EqualCriterion(entry.getKey(), entry.getValue()));
        }
        odb = ODBFactory.open(DATABASE);
        Objects objects = odb.getObjects(query);
        if (objects.size() != 1) {
            throw new IllegalArgumentException("Too many hits. Use findStorables() method in stead.");
        } else {
            return (T) objects.getFirst();
        }
    }

    public <T extends Comparable> T findComparable(Class itemClassToFind, Map<String, String> criteria) throws Exception {
        CriteriaQuery query = new CriteriaQuery(itemClassToFind);
        for (Entry<String, String> entry : criteria.entrySet()) {
            query.setCriterion(new EqualCriterion(entry.getKey(), entry.getValue()));
        }
        odb = ODBFactory.open(DATABASE);
        Objects objects = odb.getObjects(query);
        if (objects.size() != 1) {
            throw new IllegalArgumentException("Too many hits. Use findComparables() method in stead.");
        } else {
            return (T) objects.getFirst();
        }
    }
}
